use tauri::{
    tray::{TrayIconBuilder, TrayIconEvent, MouseButton, MouseButtonState},
    AppHandle,
    Result,
    Manager,
    WindowEvent
};

/// 创建托盘图标
#[tauri::command]
pub async fn create_tray(app_handle: AppHandle) -> Result<()> {
    // 检查托盘是否已存在
    if app_handle.tray_by_id("tray").is_some() {
        return Ok(());
    }

    // 获取应用图标
    let icon = app_handle.default_window_icon()
       .ok_or_else(|| tauri::Error::InvalidIcon(
           *Box::new(
               std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "Failed to get default window icon"
                 )
               )
           )
       )?
       .clone();

    // 克隆app_handle用于事件处理闭包
    let app_clone = app_handle.clone();

    // 创建托盘并设置点击事件
    let _ = TrayIconBuilder::with_id("tray")
        .tooltip("Tauri仿微信")
        .icon(icon)
        .on_tray_icon_event(move |_tray, event| match event {
            TrayIconEvent::Click {
                id: _,
                position,
                rect: _,
                button,
                button_state,
            } => match (button, button_state) {
                (MouseButton::Left, MouseButtonState::Down) => {
                    // 左击按下：显示聊天窗口
                    println!("左击");
                    // 获取所有窗口
                    let windows = app_clone.webview_windows();

                    // 查找并显示聊天窗口
                    for (name, window) in windows {
                        if name == "login" || name == "chat" {
                            // 显示窗口
                            if let Err(e) = window.show() {
                                eprintln!("Failed to show window {}: {}", name, e);
                            }
                            // 取消最小化
                            if let Err(e) = window.unminimize() {
                                eprintln!("Failed to unminimize window {}: {}", name, e);
                            }
                            // 确保窗口显示在任务栏上，将skipTaskBar设为false
                            if let Err(e) = window.set_skip_taskbar(false) {
                                eprintln!("Failed to set skip_taskbar to false for window {}: {}", name, e);
                            }
                            // 设置焦点
                            if let Err(e) = window.set_focus() {
                                eprintln!("Failed to set focus on window {}: {}", name, e);
                            }
                            break;
                        }
                    }
                },
                (MouseButton::Right, MouseButtonState::Down) => {
                    // 右击按下：在托盘图标右上方显示托盘菜单窗口
                    println!("右击");
                    // 尝试获取托盘菜单窗口
                    if let Some(tray_window) = app_clone.get_webview_window("tray") {
                        // 为tray窗口添加失去焦点事件监听，当窗口失去焦点时自动隐藏
                        // 此处不应该加入点击时也隐藏，因为可能点击的是边框，而非自定义按钮
                        // 只注册一次失去焦点事件监听器
                        static EVENT_REGISTERED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
                        if !EVENT_REGISTERED.swap(true, std::sync::atomic::Ordering::Relaxed) {
                            let window_clone = tray_window.clone();
                            let _ = tray_window.on_window_event(move |event| {
                                if let WindowEvent::Focused(false) = event {
                                    let _ = window_clone.hide();
                                    println!("失去焦点");
                                }
                            });
                        }

                        // 获取窗口大小以正确定位
                        if let Ok(outer_size) = tray_window.outer_size() {
                            // 计算位置：托盘图标右侧，窗口顶部与托盘图标对齐
                            let window_x = position.x;
                            let window_y = position.y - outer_size.height as f64;

                            // 设置窗口位置
                            if let Err(e) = tray_window.set_position(tauri::PhysicalPosition::new(
                                window_x - 10.0,
                                window_y + 10.0
                            )) {
                                println!("Failed to set tray window position: {}", e);
                                return;
                            }

                            // 显示托盘菜单窗口
                            let _ = tray_window.set_always_on_top(true);
                            let _ = tray_window.show();
                            let _ = tray_window.set_focus();
                        }
                    }
                },
                _ => {}
                // 忽略其他按钮状态组合
            },

            _ => {}
        })
        .build(&app_handle);

    Ok(())
}

/// 销毁托盘图标
#[tauri::command]
pub async fn destroy_tray(app_handle: AppHandle) -> Result<()> {
    // 在 Tauri 中，销毁托盘图标使用 remove_tray_by_id 方法
    app_handle.remove_tray_by_id("tray");
    println!("销毁托盘图标");
    Ok(())
}
